package com.example.woke;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bean.BankAccountAndPayChannel;
import com.bean.BaseResponse;
import com.http.HttpMethods;
import com.jakewharton.rxbinding2.view.RxView;
import com.woke.adapter.UnionPayChannelAdapter;
import com.woke.data.Datas_bankedcard;
import com.woke.data.Datas_cardinfo;
import com.woke.data.Datas_nocardback;
import com.woke.data.Datas_paytype;
import com.woke.data.UnionPayChannel;
import com.woke.diyview.Alertdialogall;
import com.woke.method.Httpgetpaytype;
import com.woke.method.Httploaddata;
import com.woke.method.MyApp;
import com.woke.serizedatas.Datas_load;
import com.zhongcai.online.R;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class MywalletnocardActivity extends Activity implements OnClickListener {
	private static final String TAG = MywalletnocardActivity.class.getSimpleName ();
	private static final int REQUEST_BIND_CARD = 8;//绑卡请求
	private static final int REQUEST_AUTH_PAY_PASSWORD = 18;//支付密码验证
	private TextView mEcarno;
	private RelativeLayout mBar, mBar1;
	private Button mTok;
	private TextView mTmoney;
	private float money;
	private String order_id;
	private TextView mTorderid;
	private ImageView mView;
	private boolean show = true;
	private LinearLayout mShow1;
	private String playform;// �ж��ױ�����ī��֧��
	private MyApp application;
	//	private boolean cardbank;// �ж��Ƿ�������п������ױ�֧��������
	private ArrayList<Datas_bankedcard> mBankedCards = new ArrayList<Datas_bankedcard> ();
	private ImageView mBlidn;
	private LayoutInflater inflater;
	private boolean showed = false;
	//	private boolean isbanked = false ;//�ж��Ƿ��а󶨹����п�
//	private int currentno = 0;
	private String title;//���ʽ
	private RecyclerView mChannelRecyView;
	private ArrayList<UnionPayChannel> mUnionPayChannels = new ArrayList<> ();
	private UnionPayChannelAdapter mChannelAdapter;
	private Alertdialogall mSettingPayPaw = new Alertdialogall ();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate (savedInstanceState);
		setContentView (R.layout.activity_mywalletnocard);

		EventBus.getDefault ().register (this);

		Intent intent = getIntent ();
		money = intent.getFloatExtra ("money", 1);
		order_id = intent.getStringExtra ("order_id");
		playform = intent.getStringExtra ("playform");
		application = (MyApp) getApplication ();
		inflater = getLayoutInflater ();
		intview ();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy ();
		EventBus.getDefault ().unregister (this);

	}

	private void intview() {
		mView = (ImageView) findViewById (R.id.avmywallet_nocar_show);
		mView.setOnClickListener (this);
		mShow1 = (LinearLayout) findViewById (R.id.avmywnocar_show1);
		findViewById (R.id.avmywalletnocard_image_back).setOnClickListener (this);
		mTorderid = (TextView) findViewById (R.id.avmywalletnocar_text_orderid);
		mTorderid.setText (order_id);
		mTmoney = (TextView) findViewById (R.id.avmywallet_nocar_money);
		mTmoney.setText ("￥" + money);
		mTok = (Button) findViewById (R.id.avmywa_nocard_pay);
		RxView.clicks (mTok)
				.throttleFirst (2, TimeUnit.SECONDS)
				.subscribe (new Consumer<Object> () {
					@Override
					public void accept(Object o) throws Exception {
						//防抖动,避免多次操作
						goToNocardPay ();
					}
				});
//		mTok.setOnClickListener (this);
		mEcarno = (TextView) findViewById (R.id.avzhongcai_edit_pay);
		mBar = (RelativeLayout) findViewById (R.id.avmywallet_nocar_frame);
		mBar1 = (RelativeLayout) findViewById (R.id.avmywallet_nocar_frame1);
		mBlidn = (ImageView) findViewById (R.id.avzhongcai_image_blindbank);
		mBlidn.setOnClickListener (this);
		mChannelRecyView = (RecyclerView) findViewById (R.id.channel_recyclerView);
		LinearLayoutManager layoutManager = new LinearLayoutManager (this, LinearLayoutManager.VERTICAL, false);
		layoutManager.setSmoothScrollbarEnabled (true);
		layoutManager.setAutoMeasureEnabled (true);
		mChannelRecyView.setLayoutManager (layoutManager);
		mChannelRecyView.setHasFixedSize (true);
		mChannelRecyView.setNestedScrollingEnabled (false);
		mChannelAdapter = new UnionPayChannelAdapter (MywalletnocardActivity.this, mUnionPayChannels);
		mChannelRecyView.setAdapter (mChannelAdapter);
//		getbanklist ();
//		getUnionPayChannel ();  //获取银联通道
		getbanklistAndUnionPayChannel ();
	}

	@Override
	protected void onResume() {
		super.onResume ();
		if (application == null) {
			application = MyApp.getInstance ();
		}
		Httploaddata.uploadFile (application);
	}

	/**
	 * 获取银行卡列表和渠道
	 */
	private void getbanklistAndUnionPayChannel() {
		if (application.getDatas_load () != null) {

			int userid = Integer.parseInt (application.getDatas_load ().getId ());
			HttpMethods.getInstance ()
					.getBankAccountAndUnionPayChannel (mAccountsAndChannelsObserver, userid, 1, 3);
		}
	}

	private Observer<BankAccountAndPayChannel> mAccountsAndChannelsObserver = new Observer<BankAccountAndPayChannel> () {
		@Override
		public void onSubscribe(Disposable d) {

		}

		@Override
		public void onNext(BankAccountAndPayChannel value) {
			if (value != null) {
				List<Datas_bankedcard> baList = value.getBanklist ();
				List<UnionPayChannel> clist = value.getGalllist ();
				if (baList != null && baList.size () > 0) {
					mBankedCards.clear ();
					mBankedCards.addAll (baList);
				}
				if (mBankedCards.size () > 0) {
					if (showed == false) {
						Datas_bankedcard data = mBankedCards.get (0);
						mEcarno.setText (data.getCardno ());
					} else {
						Datas_bankedcard data = mBankedCards.get (mBankedCards.size () - 1);
						mEcarno.setText (data.getCardno ());
					}
					mTok.setEnabled (true);
//					mTok.setBackgroundDrawable (getResources ().getDrawable (R.drawable.rect_lightred));
					mBlidn.setVisibility (View.VISIBLE);

				} else {
					Toast.makeText (MywalletnocardActivity.this, "请先绑定一张银行号后在支付", Toast.LENGTH_SHORT)
							.show ();
					Intent intent = new Intent (MywalletnocardActivity.this, MywalletcardActivity.class);
					intent.putExtra ("czhiortxian", "no");
					startActivityForResult (intent, REQUEST_BIND_CARD);
					return;
				}

				if (clist != null && clist.size () > 0) {
					mUnionPayChannels.clear ();
					mUnionPayChannels.addAll (clist);
					if (mChannelAdapter != null) {
						mChannelAdapter.notifyDataSetChanged ();
					}
				}


			}
		}

		@Override
		public void onError(Throwable e) {

			Toast.makeText (MywalletnocardActivity.this, e.getMessage (), Toast.LENGTH_SHORT)
					.show ();
		}

		@Override
		public void onComplete() {

		}
	};

	private class SuccessObserver implements Observer<BaseResponse> {

		private int user_id;
		private float amount;
		private int way;
		private String card_no;

		public SuccessObserver(int user_id, float amount, int way, String card_no) {
			this.user_id = user_id;
			this.amount = amount;
			this.way = way;
			this.card_no = card_no;
		}

		@Override
		public void onSubscribe(Disposable d) {

		}

		@Override
		public void onNext(BaseResponse value) {
			if (value != null) {
				Log.e ("onError", value.toString ());
				if (value.resultSuccess ()) {
					Toast.makeText (MywalletnocardActivity.this, "充值成功", Toast.LENGTH_SHORT)
							.show ();
					finish ();
				} else {
					Toast.makeText (MywalletnocardActivity.this, "系统繁忙,请稍后重试!", Toast.LENGTH_SHORT)
							.show ();
				}
			} else {
				Toast.makeText (MywalletnocardActivity.this, "系统繁忙,请稍后重试!", Toast.LENGTH_SHORT)
						.show ();
			}
		}

		@Override
		public void onError(Throwable e) {
			Log.e ("onError", e.getMessage ());
			if (e.getMessage ().equals ("unbind")) {
				//未绑卡
				HttpMethods.getInstance ()
						.bindingBankAccount (mBindingObserver, user_id, 1, card_no);
			} else {
				Toast.makeText (MywalletnocardActivity.this, e.getMessage (), Toast.LENGTH_SHORT)
						.show ();
			}
		}

		@Override
		public void onComplete() {

		}
	}

	private Observer<BaseResponse<String>> mBindingObserver = new Observer<BaseResponse<String>> () {


		@Override
		public void onSubscribe(Disposable d) {

		}

		@Override
		public void onNext(BaseResponse<String> value) {
			if (value != null) {
				if (value.resultSuccess ()) {
					Intent intent = new Intent (MywalletnocardActivity.this, UnionPayBindActivity.class);
					intent.putExtra ("html", value.getData ().getData ());
					startActivity (intent);
				}
			}

		}

		@Override
		public void onError(Throwable e) {
			Log.e ("onError", e.getMessage ());
			Toast.makeText (MywalletnocardActivity.this, e.getMessage (), Toast.LENGTH_SHORT)
					.show ();
		}

		@Override
		public void onComplete() {

		}
	};


	private void getpaytype() {
		String getbanked = Httpgetpaytype.getbanked (mBar);
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onEventMainThread(Datas_paytype event) {
		title = event.title;
	}
	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onEventMainThread(Datas_nocardback event) {
		showed = true;

	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onEventMainThread(Datas_cardinfo event) {
		String isvalid = event.getIsvalid ();// �Ƿ���Ч��
		if (isvalid.equals ("0")) {
			Toast.makeText (MywalletnocardActivity.this, "无效的银行卡", Toast.LENGTH_SHORT).show ();
		} else {//
			String cardno = mEcarno.getText ().toString ();
			Datas_nocardback nocarback = new Datas_nocardback ();
			nocarback.setCardno (cardno);
			nocarback.setMoney (money);
			nocarback.setId (order_id);
			nocarback.setBank (event.getBankname ());
			nocarback.setCardtype (event.getCardtype ());
			Intent intent = new Intent (MywalletnocardActivity.this, NocardpayActivity.class);
			intent.putExtra ("cardlist", nocarback);
			intent.putExtra ("title", title);
			startActivity (intent);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult (requestCode, resultCode, data);

		if (requestCode == 120 && resultCode == 97) {
			ArrayList<String> listnew = data.getStringArrayListExtra ("nocarpay");
			mEcarno.setText (listnew.get (2));
		} else if (requestCode == REQUEST_BIND_CARD) {
			getbanklistAndUnionPayChannel ();
		} else if (requestCode == REQUEST_AUTH_PAY_PASSWORD && resultCode == 600) {
			Log.e ("adf", "1");
			if (data != null) {
				Log.e ("adf", "2");
				boolean isRight = data.getBooleanExtra ("paypsw", false);
				if (isRight) {
					Log.e ("adf", "3");
					String cardno = mEcarno.getText ().toString ();

					if (mChannelAdapter == null || mChannelAdapter.getWay () == - 1) {
						Log.e ("adf", "" + 32);
						isBindedToRecharge (Integer.parseInt (application.getDatas_load ()
								.getId ()), money, 1, cardno);
					} else {
						Log.e ("adf", "=" + 33);
						isBindedToRecharge (Integer.parseInt (application.getDatas_load ()
								.getId ()), money, mChannelAdapter.getWay (), cardno);
					}
				} else {
					Log.e ("adf", "31");
					Toast.makeText (MywalletnocardActivity.this, "请输入正确支付密码", Toast.LENGTH_SHORT)
							.show ();
				}
			}

		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId ()) {
			case R.id.avmywalletnocard_image_back:
				InputMethodManager imm = (InputMethodManager) getSystemService (Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow (mEcarno.getWindowToken (), 0); // ǿ�����ؼ���
				finish ();
				break;

			case R.id.avmywallet_nocar_show:
				if (show == true) {
					mShow1.setVisibility (View.VISIBLE);
					mView.setImageDrawable (getResources ().getDrawable (
							R.drawable.avmywallet_nocard_up));
					show = false;
				} else {
					mShow1.setVisibility (View.GONE);
					mView.setImageDrawable (getResources ().getDrawable (R.drawable.avmywallet_nocard_down));
					show = true;
				}
				break;

//			case R.id.avmywa_nocard_pay:
//				goToNocardPay ();
//				break;

			case R.id.avzhongcai_image_blindbank:
				Intent intent = new Intent (MywalletnocardActivity.this, MybankblindActivity.class);
				intent.putExtra ("czhiortxian", "nocarpay");
				startActivityForResult (intent, 120);
				break;

			default:
				break;
		}
	}

	/**
	 * 确认,进行支付判断
	 */
	private void goToNocardPay() {
		mTok.setFocusableInTouchMode (true);
		mTok.setFocusable (true);
		mTok.requestFocus ();
		String cardno = mEcarno.getText ().toString ();
		if (null == cardno || cardno.equals ("")) {
			Toast.makeText (MywalletnocardActivity.this, "请选择银行卡", Toast.LENGTH_SHORT)
					.show ();
		} else {
			if (mBankedCards.size () > 0) {
				Datas_load datasLoad = application.getDatas_load ();
				if (datasLoad != null) {
					if (TextUtils.isEmpty (datasLoad.getPay_pwd ())) {
						mSettingPayPaw.aralogid (MywalletnocardActivity.this, "还未设置支付密码", "前往设置？");
					} else {
						Intent intent1 = new Intent (MywalletnocardActivity.this, CheckpaypswActivity.class);
						intent1.putExtra ("paymoney", String.valueOf (money));
						intent1.putExtra (CheckpaypswActivity.KEY_PAY_TYPE, "chongzhi");
						startActivityForResult (intent1, REQUEST_AUTH_PAY_PASSWORD);
					}
				} else {
					Toast.makeText (this, "登录超时,请重新登录", Toast.LENGTH_SHORT).show ();
				}


			}
		}
	}


	private void isBindedToRecharge(int user_id, float amount, int way, String card_no) {
		SuccessObserver mSuccessObserver = new SuccessObserver (user_id, amount, way, card_no);
		HttpMethods.getInstance ()
				.isBindedToRecharge (mSuccessObserver, user_id, amount, 1, card_no);

	}

}
